//## 거래명세서 정보 저장 ####################
function fnSave()
{
	if (!$("#compCd").val())
	{
		alert("거래처를 선택해 주세요!");
		$("#compNm").focus();
		return;
	}
	if (!$("#incomeDt").val())
	{
		alert("발행일 바르게 입력해 주세요!");
		$("#incomeDt").focus();
		return;
	}
	if ($("#billCd").val())
	{
		alert("거래명세서 수정은 메모만 가능합니다.");
	}
	var valUrl  = '/action/bizBill/save.asp';
		var param = "compCd="+$("#compCd").val();
		param += "&income="+encodeURIComponent($("#income").val());
		param += "&billMemo="+encodeURIComponent($("#billMemo").val());
		param += "&billCd="+$("#billCd").val();
		param += "&incomeDt="+$("#incomeDt").val();
		param += "&amount="+$("#amount").val();
		param += "&orgAmount="+$("#orgAmount").val();
		param += "&tax="+$("#tax").val();
		param += "&part="+$("#part").val();
		param += "&flag="+$("#flag").val();
	
	if (xMode=="debug") window.open(valUrl+'?xMode=debug&'+param);

	$.ajax({
		url: valUrl,
		type: 'POST',
		dataType: 'xml',
		data: param,
		success: function(xml){
			fnSessionCheck($(xml).find("MSG").text());
			if ($(xml).find("MSG").text() == "Save OK!")
			{
				alert("Save OK!\n거래명세서 항목을 등록해 주세요.");
				grid01List(1);
				fnReset();
			}
			else alert($(xml).find("MSG").text());
		},
		error: function(xml){
			alert('Error!!');
			alert(xml.responseText);
		}
	});
}

//## 거래 품목 정보 저장 ####################
function fnSaveArticle()
{
	if (!$("#billCd").val())
	{
		alert("거래명세서를 먼저 선택해 주세요!");
		return;
	}
	if (!$("#prdNm").val())
	{
		alert("품목명을 바르게 입력해 주세요!");
		$("#prdNm").focus();
		return;
	}
	var valUrl  = '/action/bizBill/saveArticle.asp';
		var param = "billCd="+$("#billCd").val();
		param += "&fullLotNo="+$("#fullLotNo").val();
		param += "&lotSubNo="+$("#lotSubNo").val();
		param += "&rank="+$("#rank").val();
		param += "&prdNm="+encodeURIComponent($("#prdNm").val());
		param += "&orderNo="+encodeURIComponent($("#orderNo").val());
		param += "&orderPrdCd="+encodeURIComponent($("#orderPrdCd").val());
		param += "&goodQty="+$("#goodQty").val();
		param += "&unitPrice="+$("#unitPrice").val();
		param += "&totalPrice="+$("#totalPrice").val();
		param += "&compCd="+$("#compCd").val();
		param += "&flag="+$("#articleFlag").val();

	if (xMode=="debug") window.open(valUrl+'?xMode=debug&'+param);

	$.ajax({
		url: valUrl,
		type: 'POST',
		dataType: 'xml',
		data: param,
		success: function(xml){
			fnSessionCheck($(xml).find("MSG").text());
			if ($(xml).find("MSG").text() == "Save OK!")
			{
				alert("Save OK!");
				grid02List(1);
				fnResetArticle();
			}
			else alert($(xml).find("MSG").text());
		},
		error: function(xml){
			alert('Error!!');
			alert(xml.responseText);
		}
	});
}

function fnPrint()
{
	if($("#billCd").val())
	{
		window.open("/printBizBill.asp?billCd="+$("#billCd").val());
	}
	else
	{
		alert("거래명세서를 선택해 주세요");
	}
}

//## 거래 정보 그리드 표시 ####################
var G_curPage01 = 1;

function grid01List(page)
{	
	var gridNo = 1;
	var xmlNode = "BizIncome";

	fnResetGrid(gridNo);
	fnNewLoading(gridNo);

	if (!page) page = G_curPage01;
	if (page == undefined) page = 1;
	else G_curPage01 = page;
	var limit = 50;

	var valUrl = "/action/bizBill/list.asp";
	var Parm = "findStartDt="+$("#findStartDt").val();
		Parm += "&findEndDt="+$("#findEndDt").val();
		Parm += "&findPrdNm="+$("#findPrdNm").val();
	if (xMode=="Debug") window.open(valUrl+'?xMode=debug&'+Parm);

	// 그리드 헤더를 기준으로 Cell의 폭을 구해온다.
	var cellWidth = fnGetGridCellWidth(gridNo);	
	// Cell의 정렬방식
	var cellAlign = ",,,,right,right,right,".split(",");
	// Cell의 링크 걸지 여부 결정
	var cellLink = ",,,,,,,,,,".split(",");

	$.ajax({
		url: valUrl,
		type: 'POST',
		dataType: 'xml',
		data: Parm,
		success: function(xml){
			var gridList = "";
			var k = 1;
			var ttlCnt = $(xml).find(xmlNode).length;
			var startNo = (parseInt(page,10)-1) * limit;
			var endNo = parseInt(page,10) * limit;
			var bgColor = "#FFF";
			var chkCnt = 0;
			
			// 그리드의 부가 정보(레코드수, 페이징) 표시 또는 가리기
			fnGridExtraInfo(gridNo, ttlCnt, page, limit); 

			if (ttlCnt <= endNo) endNo = ttlCnt;
			var no = endNo;
			var ttlGood = 0;
			var ttlBad = 0;
			var ttlQty = 0;
			$(xml).find(xmlNode).each(function(idx){

				if (k>startNo && k<=endNo)
				{
					var billCd			= $(this).find('billCd').text();
					var income			= $(this).find('income').text();
					var company			= $(this).find('company').text();
					var incomeDt		= $(this).find('incomeDt').text();
					var amount			= $(this).find('amount').text();
					var orgAmount	= $(this).find('orgAmount').text();
					var tax					= $(this).find('tax').text();
					var flag					= $(this).find('flag').text();
					
					var arrVal = new Array();
					arrVal[0] = "<p>"+billCd+"</p>";
					arrVal[1] = "<p>"+company+"</p>";
					arrVal[2] = "<p>"+income+"</p>";
					arrVal[3] = "<p>"+incomeDt.split("-").join(".")+"</p>";
					arrVal[4] = "<p>"+orgAmount+"</p>";
					arrVal[5] = "<p>"+tax+"</p>";
					arrVal[6] = "<p>"+amount+"</p>";
					
					if (flag == "N") bgColor = "#EEE";
					else bgColor = "#FFF";
					
					var link = "fnBizBillDetail('"+billCd+"')";

					//gridList = fnDrawCell(lotYear, lotNo, lotSubNo, processCd);
					gridList = fnDrawCell(arrVal, bgColor, cellWidth, cellAlign, '', link, cellLink);

					$("#"+"gridBody"+gridNo).append(gridList);
				}
				no = parseInt(endNo,10)-parseInt(k,10);
				k++;			
			});
		},
		error: function(xml){
			alert('Error!!\r\n'+xml.responseText);
		}
	});

}

//## 거래 상세정보 표시 ####################
function fnBizBillDetail(billCd)
{
	var valUrl = "/action/bizBill/view.asp";
	var param = "billCd="+billCd;

	if (xMode=="debug") window.open(valUrl+'?xMode=debug&'+param);

	$.ajax({
		url: valUrl,
		type: 'POST',
		dataType: 'xml',
		data: param,
		success: function(xml){

			//## 로그인 체크
			fnSessionCheck($(xml).find("MSG").text());
			fnReset();			
			$("#billCd").val($(xml).find("billCd").text());
			$("#income").val($(xml).find("income").text());
			$("#incomeDt").val($(xml).find("incomeDt").text());
			$("#amount").val($(xml).find("amount").text());
			$("#orgAmount").val($(xml).find("orgAmount").text());
			$("#tax").val($(xml).find("tax").text());
			$("#part").val($(xml).find("part").text());
			$("#orderNo").val($(xml).find("orderNo").text());
			$("#billMemo").val($(xml).find("billMemo").text());
			$("#flag").val($(xml).find("flag").text());
			fnFindCompany('',$(xml).find("compCd").text(),'compCd');	
			//$("#btnSave1").css("display","none");
			grid02List(1);

		},
		error: function(xml){
			alert('Error!!');
			alert(xml.responseText);
		}
	});
}

//## 거래 품목 그리드 표시 ####################

var G_curPage02 = 1;

function grid02List(page)
{	
	var gridNo = 2;
	var xmlNode = "Article";

	fnResetGrid(gridNo);
	fnNewLoading(gridNo);

	if (!page) page = G_curPage01;
	if (page == undefined) page = 1;
	else G_curPage01 = page;
	var limit = 50;

	var _billCd = $("#billCd").val();
	if (_billCd == "")  _billCd = 0;
	var valUrl = "/action/bizBill/listArticle.asp";
	var Parm = "billCd="+_billCd;
	
	if (xMode=="Debug") window.open(valUrl+'?xMode=debug&'+Parm);

	// 그리드 헤더를 기준으로 Cell의 폭을 구해온다.
	var cellWidth = fnGetGridCellWidth(gridNo);	
	// Cell의 정렬방식
	var cellAlign = ",left,,right,right,right,".split(",");
	// Cell의 링크 걸지 여부 결정
	var cellLink = ",,,,,,,,,,".split(",");

	$.ajax({
		url: valUrl,
		type: 'POST',
		dataType: 'xml',
		data: Parm,
		success: function(xml){
			var gridList = "";
			var k = 1;
			var ttlCnt = $(xml).find(xmlNode).length;
			var startNo = (parseInt(page,10)-1) * limit;
			var endNo = parseInt(page,10) * limit;
			var bgColor = "#FFF";
			var chkCnt = 0;
			
			// 그리드의 부가 정보(레코드수, 페이징) 표시 또는 가리기
			fnGridExtraInfo(gridNo, ttlCnt, page, limit); 

			if (ttlCnt <= endNo) endNo = ttlCnt;
			var no = endNo;
			var ttlGood = 0;
			var ttlBad = 0;
			var ttlQty = 0;
			$(xml).find(xmlNode).each(function(idx){
				if (k>startNo && k<=endNo)
				{
					var lotYear		= $(this).find('lotYear').text();
					var lotNo			= $(this).find('lotNo').text();
					var lotSubNo	= $(this).find('lotSubNo').text();
					var rank			= $(this).find('rank').text();
					var goodQty	= $(this).find('goodQty').text();
					var orderNo		= $(this).find('orderNo').text();
					var unitPrice	= $(this).find('unitPrice').text();
					var totalPrice	= $(this).find('totalPrice').text();
					var prdNm		= $(this).find('prdNm').text();
					var flag			= $(this).find('flag').text();
					
					var arrVal = new Array();
					arrVal[0] = "<p>"+no+"</p>";
					arrVal[1] = "<p>"+prdNm+"</p>";
					arrVal[2] = "<p>"+orderNo+"</p>";
					arrVal[3] = "<p>"+goodQty+"</p>";
					arrVal[4] = "<p>"+unitPrice+"</p>";
					arrVal[5] = "<p>"+totalPrice+"</p>";
					
					var link = "fnBizBillArticleDetail('"+lotYear+"','"+lotNo+"','"+lotSubNo+"','"+rank+"')";

					//gridList = fnDrawCell(lotYear, lotNo, lotSubNo, processCd);
					gridList = fnDrawCell(arrVal, bgColor, cellWidth, cellAlign, '', link, cellLink);

					$("#"+"gridBody"+gridNo).append(gridList);
				}
				no = parseInt(endNo,10)-parseInt(k,10);
				k++;			
			});
		},
		error: function(xml){
			alert('Error!!\r\n'+xml.responseText);
		}
	});

}

//## 거래 품목 상세 정보
function fnBizBillArticleDetail(lotYear, lotNo, lotSubNo, rank)
{
	var valUrl = "/action/bizBill/viewArticle.asp";
	var param = "billCd="+$("#billCd").val();
		  param += "&lotYear="+lotYear;
		  param += "&lotNo="+lotNo;
		  param += "&lotSubNo="+lotSubNo;
		  param += "&rank="+rank;

	var fullLotNo = lotYear+lotNo;
	
	if (xMode=="debug") window.open(valUrl+'?xMode=debug&'+param);

	$.ajax({
		url: valUrl,
		type: 'POST',
		dataType: 'xml',
		data: param,
		success: function(xml){
			
			//## 로그인 체크
			fnSessionCheck($(xml).find("MSG").text());
			fnResetArticle();			
			$("#fullLotNo").val(fullLotNo);
			$("#lotSubNo").val(lotSubNo);
			$("#rank").val(rank);
			$("#prdNm").val($(xml).find("prdNm").text());
			$("#orderNo").val($(xml).find("orderNo").text());
			$("#orderPrdCd").val($(xml).find("orderPrdCd").text());
			$("#unitPrice").val($(xml).find("unitPrice").text());
			$("#goodQty").val($(xml).find("goodQty").text());
			$("#totalPrice").val($(xml).find("totalPrice").text());
			$("#articleFlag").val($(xml).find("flag").text());
			$("#btnSave2").val("저장");

		},
		error: function(xml){
			alert('Error!!');
			alert(xml.responseText);
		}
	});

}

//## 명세서 메일 발송
function fnEmail()
{
	if (!$("#billCd").val())
	{
		alert("거래명세서를 먼저 선택해 주세요!");
		return;
	}
	if (!$("#toEmail").val())
	{
		alert('E-mail을 바르게 입력해 주세요!');
		$("#toEmail").focus();
		return;
	}
	if (confirm("메일을 발송 하시겠습니까?"))
	{
		$("#btnMail").val("발송중...");
		var valUrl = "/action/bizBill/sendEmail.asp";
		var param = "billCd="+$("#billCd").val();
			  param += "&toEmail="+$("#toEmail").val();
		
		if (xMode=="debug") window.open(valUrl+'?xMode=debug&'+param);
	
		$.ajax({
			url: valUrl,
			type: 'POST',
			dataType: 'xml',
			data: param,
			success: function(xml){
	
				//## 로그인 체크
				fnSessionCheck($(xml).find("MSG").text());
	
				if ($(xml).find("MSG").text() == "Save OK!")
				{
					alert("거래명세서가 Mail로 발송 되었습니다.");
				}
				else alert($(xml).find("MSG").text());
			},
			error: function(xml){
				alert('Error!!');
				alert(xml.responseText);
			}
		});

		$("#btnMail").val("메일발송");
	}
}

//##  명세서 품목 금액 구하기
function fnGetArticleTotal()
{
	var amt = $("#goodQty").val();
	amt = amt.split(",").join("");
	var unitPrice = $("#unitPrice").val();
	unitPrice = unitPrice.split(",").join("");
	if (!amt) amt = 0;	
	if (!unitPrice) unitPrice = 0;
	var articlePrice = parseInt(amt,10)*parseInt(unitPrice,10);
	$("#totalPrice").val(getNumWithComma(articlePrice));
}

//## 부가세 구하기
function fnAutoTax(obj,target)
{
	var amount = obj.value.split(",").join("");
	var tax = parseInt(amount,10)/10;
	$("#"+target).val(getNumWithComma(tax));
}

//## 합계 구하기
function fnGetTotal(amt, taxObj, target)
{
	var amount = $("#"+amt).val().split(",").join("");
	var tax = taxObj.value.split(",").join("");
	
	var ttlAmount = parseInt(amount,10)+parseInt(tax,10);
	$("#"+target).val(getNumWithComma(ttlAmount));
}

//## 거래명세서 정보 Reset 기능
function fnReset()
{
	$("#billCd").val("");
	$("#income").val("");
	$("#incomeDt").val("");
	$("#amount").val("");
	$("#compCd").val("");
	$("#compNm").val("");
	$("#orgAmount").val("");
	$("#tax").val("");
	$("#billMemo").val("");
	$("#part").val("");
	$("#toEmail").val("");
	$("#flag").val("Y");
	//$("#btnSave1").css("display","");
}

//## 거래 품목 정보 Reset 기능
function fnResetArticle()
{
	$("#fullLotNo").val("");
	$("#lotSubNo").val("");
	$("#rank").val("");
	$("#prdNm").val("");
	$("#unitPrice").val("");
	$("#goodQty").val("");
	$("#totalPrice").val("");
	$("#orderNo").val("");
	$("#orderPrdCd").val("");
	$("#articleFlag").val("Y");

}

//## 검색 Reset 기능
function fnSearchReset()
{
	$("#findOrderNo").val("");
	$("#findCompany").val("");
	$("#findPrdCd").val("");
	$("#findPrdNm").val("");
}